<?php

namespace App\Http\Controllers\Admin\Config;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use App\Models\Category;
use DB;
use Validator;
use Log;
class CategoryController extends AdminController
{
    /**
	 * 更新
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
    function postUpdate(Request $request){
    	$validator = $this->formValidator($request->all());
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
        $id = $request->input('id');
        $pid = $request->input('pid');
        $lft = $rgt = $level =  $root_pid = 0;
        if($id){
			$category = $this->_get_one($id);
        }
        //添加子节点,获取父节点的左值和右值
        if($pid){
        	$parentCategory = $this->_get_one($pid);
        	$lft = $parentCategory->lft;
        	$rgt = $parentCategory->rgt;
        	$level = $parentCategory->level;
        	$root_pid = $parentCategory->root_pid;
            //新增子节点,判定该节点下是否已存在数据
            if(!$id){
                // $count = DB::table('property_company')->where('category_id',$pid)->count();
                // if($count>0){
                //     $this->ajaxJson(1,'添加失败,无法添加子分类到已有数据的分类,请转移该分类的数据');
                // }
            }
        }

        $data = [
			'name'     => $request->input('name'),
			'root_pid' => $root_pid,
			'pid'      => $pid,
			'lft'      => $lft+1,
			'rgt'      => $lft+2,
			'level'    => $level+1,
        ];

        DB::beginTransaction();
        try {
            if($id){
        		$data['updated_at'] = date('Y-m-d H:i:s');
                unset($data['lft'],$data['rgt'],$data['level']);
        		DB::table('category')->where('id',$id)->update($data);
        	}else{
                DB::table('category')
                    ->where('root_pid',$root_pid)
                    ->where('lft','>',$lft)
                    ->increment('lft',2);
                DB::table('category')
                    ->where('root_pid',$root_pid)
                    ->where('rgt','>',$lft)
                    ->increment('rgt',2);
                if($pid){
                    $data['created_at'] = date('Y-m-d H:i:s');
                    $data['updated_at'] = date('Y-m-d H:i:s');
                    DB::table('category')->insert($data);
                }else{
                    $data['created_at'] = date('Y-m-d H:i:s');
                    $data['updated_at'] = date('Y-m-d H:i:s');
                    $id = DB::table('category')->insertGetId($data);
                    DB::table('category')->where('id',$id)->update(['root_pid'=>$id]);
                }
            }
        	DB::commit();
            $this->ajaxJson(0,'分类创建成功');
        } catch (\Exception $e) {
        	DB::rollback();
        	Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'创建失败,请重试');
        }
    }

    /**
     * 获取树形结构数据
     * @return [type] [description]
     */
    function getTree(){
    	$data = Category::select('id','name as title','pid')->get()->toArray();
    	$parent = array();
    	foreach ($data as $key => $value) {
    		if(!$value['pid']){
    			$parent[] = $value;
    			unset($data[$key]);
    		}
    	}
    	foreach ($parent as $key => $value) {
    		$result = $this->formatTreeData($data,$value['id']);
    		if($result){
    			$parent[$key]['children'] = $result;
    			$parent[$key]['expand'] = true;
    		}
    	}
    	$this->ajaxJson(0,'',$parent);
    }

    /**
     * 删除一个节点
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function deleteOne($id){
        $category = $this->_get_one($id);
        //获取当前节点下所有的子节点
        $childrens = DB::table('category')->where('root_pid',$category->root_pid)->where('lft','>',$category->lft)->where('rgt','<',$category->rgt)->get()->toArray();
        $childrenCount = 1;//子节点个数,自己算一个节点
        $childrensIdArr = [];
        if(!empty($childrens)){
            $childrensIdArr = array_pluck($childrens,'id');
            //查找分类下是否有数据
            // $count = DB::table('property_company')->whereIn('category_id',$childrensIdArr)->count();
            // if($count>0){
            //     $this->ajaxJson(0,'删除失败,当前分类或子分类已有数据,请删除分类下的所有数据或转移到其他分类下');
            // }
            $childrenCount = count($childrens)+1;
        }
        //追加本身节点
        $childrensIdArr[] = $category->id;
        DB::beginTransaction();
        try {
            DB::table('category')->whereIn('id',$childrensIdArr)->delete();
            DB::table('category')->where('root_pid',$category->root_pid)->where('lft','>',$category->lft)->decrement('lft',2*$childrenCount);
            DB::table('category')->where('root_pid',$category->root_pid)->where('rgt','>',$category->lft)->decrement('rgt',2*$childrenCount);
            DB::commit();
            $this->ajaxJson(0,'删除成功');
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'删除失败,请重试');
        }
    }

    /**
     * 格式化树形数据
     * @param  [type] $data [description]
     * @param  [type] $pid  [description]
     * @return [type]       [description]
     */
    private function formatTreeData($data,$pid){
    	$list = array();
    	foreach ($data as $key => $value) {
    		if($value['pid']==$pid){
    			$result  = $this->formatTreeData($data,$value['id']);
    			if(!empty($result) && count($result)>0){
    				$value['children'] = $result;
    				$value['expand'] = true;
    			}
    			$list[] = $value;
    		}
    	}
    	return $list;
    }

    /**
     * 表单验证
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    private function formValidator(array $data){
        $attribute =  array(
            'name' => '名称',
        );

        $message  = array(
            'required' => ':attribute必须填写',
        );

        return Validator::make($data, [
            'name' => 'bail|required',
        ],$message,$attribute);
    }

    /**
     * 获取单个数据
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    private function _get_one($id){
    	$category = Category::find($id);
    	if(!$category){
    		$this->ajaxJson(1,'未知的分类');
    	}
    	return $category;
    }
}
